package org.luckyjourney.controller;

import org.luckyjourney.config.LocalCache;
import org.luckyjourney.config.QiNiuConfig;
import org.luckyjourney.entity.File;
import org.luckyjourney.entity.Setting;
import org.luckyjourney.holder.UserHolder;
import org.luckyjourney.service.FileService;
import org.luckyjourney.service.SettingService;
import org.luckyjourney.util.R;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/luckyjourney/file")
public class FileController implements InitializingBean {


    @Autowired
    FileService fileService;

    @Autowired
    QiNiuConfig qiNiuConfig;

    @Autowired
    SettingService settingService;

    /**
     * @param fileKey 七牛七牛callback文件key
     * 保存到文件表
     * 上传到七牛后，七牛callback，将文件保存到数据库的文件表
     * @return
     */
    @PostMapping
    public R save(String fileKey) {
        return R.ok().data(fileService.save(fileKey, UserHolder.get()));
    }

    @GetMapping("/getToken")
    public R token(String type) {

        return R.ok().data(qiNiuConfig.uploadToken(type));
    }

    /**
     *
     * @param fileId  前端中展示的视频，点击后是会返回fileId，在数据库中存储的fileId
     * @throws IOException
     */
    @GetMapping("/{fileId}")
    public void getUUid(HttpServletRequest request, HttpServletResponse response, @PathVariable Long fileId) throws IOException {

     /**
        String ip = request.getHeader("referer");
        if (!LocalCache.containsKey(ip)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
      */
        // 设置文件filekey，加一个uuid
        File uuidFile = fileService.getFileTrustUrl(fileId);// File: FileKey（文件地址） = 域名/fileKey?uuid=随机数

        response.setContentType(uuidFile.getType());
        ///1、 重定向到七牛云获取资源
        response.sendRedirect(uuidFile.getFileKey());//七牛云会校验uuid是否合法
    }
    // 2、回调鉴权服务
    // 如果uuid是伪造的，那么说明是伪造的，直接返回401。如果存在，那么说明是合法的，直接返回200
    @PostMapping("/auth")
    public void auth(@RequestParam(required = false) String uuid, HttpServletResponse response) throws IOException {
        if (uuid == null || LocalCache.containsKey(uuid) == null) {
            response.sendError(401);
        } else {
            //删除本地缓存中的uuid
            LocalCache.rem(uuid);
            response.sendError(200);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        final Setting setting = settingService.list(null).get(0);
        for (String s : setting.getAllowIp().split(",")) {
            LocalCache.put(s, true);
        }
    }
}
